package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.SysPermission;
import com.itljm.cxrMarket.entity.SysRolePermission;
import com.itljm.cxrMarket.entity.dto.RolePermissionDTO;
import com.itljm.cxrMarket.service.SysRolePermissionService;
import com.itljm.cxrMarket.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljm
 * @date 2024/12/17 21:49
 */
@RestController
@RequestMapping("/sysRolePermission")
@CrossOrigin
public class SysRolePermissionController {
    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    /**
     * 查询所有权限
     */
    @GetMapping("/permissions")
    public Result getAllPermissions() {
        List<SysPermission> sysRolePermissions = sysRolePermissionService.selectAllPermission();
        // 转换为树形结构
        List<SysPermission> list = TreeUtil.listToTree(sysRolePermissions);
        return Result.ok(list);
    }

    /**
     * 分配权限给角色
     */
    @PostMapping("/permissions/{roleId}")
    public Result assignPermissionsToRole(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        sysRolePermissionService.assignPermissionsToRole(roleId, permissionIds);
        return Result.ok();
    }

    /**
     * 获取角色的权限列表
     */
    @GetMapping("/permissions/{roleId}")
    public Result getRolePermissions(@PathVariable Long roleId) {
        List<RolePermissionDTO> sysRolePermissions = sysRolePermissionService.selectPermissionByRoleId(roleId);
        return Result.ok(sysRolePermissions);
    }
}
